﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Data.Model;
using Newtonsoft.Json;
using ZLCMS.Business.Util;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text;
using NHibernate.Criterion;
using ZLCMS.Business.WeixinService;

namespace ZLCMS.Web.SystemManage.weixin.Menu
{
    public partial class TreeInterface : System.Web.UI.Page
    {
        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            string opt = Request["opt"];
            if (opt == "load_data")
            {
                LoadData();
            }
            else if (opt == "update")
            {
                Update();
            }
            else if (opt == "update_ex")
            {
                UpdateEx();
            }
            else if (opt == "update_weixin")
            {
                UpdateWeixin();
            }
            else if (opt == "add")
            {
                Add();
            }
            else if (opt == "remove")
            {
                Remove();
            }
        }

        public void LoadData()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                IList<WxMenu> list = session.CreateQuery("from WxMenu where OwnerAccount = '" + _userAccount + "' order by ItemSort").List<WxMenu>();

                Response.Write(JsonConvert.SerializeObject(list));
                Response.End();
            }
        }

        public void Add()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                WxMenu item = new WxMenu();
                item.ItemText = Request["ItemText"];

                int parentId = 0;
                Int32.TryParse(Request["ParentId"], out parentId);
                item.ParentId = parentId;
                item.OwnerAccount = _userAccount;

                session.Save(item);
                session.Flush();

                Response.Write(JsonConvert.SerializeObject(item));
                Response.End();
            }
        }

        public void Update()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                WxMenu item = session.CreateCriteria<WxMenu>().Add(Expression.Eq("Id", Int32.Parse(Request["Id"]))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMenu>();
                item.ItemText = Request["ItemText"];
                session.Update(item);
                session.Flush();

                Response.Write(JsonConvert.SerializeObject(item));
                Response.End();
            }
        }

        public void UpdateEx()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                WxMenu item = session.CreateCriteria<WxMenu>().Add(Expression.Eq("Id", Int32.Parse(Request["Id"]))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMenu>();
                item.ItemSort = Int32.Parse(Request["ItemSort"]);
                item.ItemType = Request["ItemType"];
                item.ItemValue = Request["ItemValue"];
                session.Update(item);
                session.Flush();

                Response.Write(JsonConvert.SerializeObject(item));
                Response.End();
            }
        }

        public void GetChildNodeIds(IList<WxMenu> list, int id, ref List<int> ids)
        {
            foreach (WxMenu type in list)
            {
                if (type.Id == id)
                {
                    ids.Add(type.Id);
                }
                if (type.ParentId == id)
                {
                    GetChildNodeIds(list, type.Id, ref ids);
                }
            }
        }

        protected void Remove()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                int nodeId = Int32.Parse(Request["Id"]);

                IList<WxMenu> list = session.CreateQuery("from WxMenu where OwnerAccount = '" + _userAccount + "'").List<WxMenu>();
                List<int> ids = new List<int>();

                GetChildNodeIds(list, nodeId, ref ids);

                session.CreateQuery("delete from WxMenu where OwnerAccount = '" + _userAccount + "' and Id in (:ids)")
                    .SetParameterList("ids", ids.ToArray())
                    .ExecuteUpdate();

                session.Flush();
                Response.Write("ok");
                Response.End();
            }
        }

        public class menu_object
        {
            public menu_object()
            {
                button = new List<object>();
            }

            public IList<object> button { get; set; }
        }

        public class sub_menu_object
        {
            public sub_menu_object()
            {
                sub_button = new List<object>();
            }

            public string name { get; set; }

            public IList<object> sub_button { get; set; }
        }

        protected JObject GetMenuItemJsonObject(WxMenu item)
        {
            JObject jobj = new JObject();
            jobj["name"] = item.ItemText;
            if (item.ItemType == "1")
            {
                jobj["type"] = "click";
                jobj["key"] = item.Id.ToString();
            }
            else if (item.ItemType == "0" || item.ItemType == "view")
            {
			
                jobj["type"] = "view";
                jobj["url"] = item.ItemValue;
            }
            else
            {
                jobj["type"] = item.ItemType;
                jobj["key"] = item.Id.ToString();
            }
            return jobj;
        }

        protected string GetMenuString()
        {
            menu_object result = new menu_object();


            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {

                IList<WxMenu> rootList = session.CreateQuery("from WxMenu where ParentId=0 and OwnerAccount = '" + _userAccount + "' order by ItemSort").List<WxMenu>();
                foreach (WxMenu root in rootList)
                {
                    IList<WxMenu> subList = session.CreateQuery("from WxMenu where ParentId=" + root.Id + " and OwnerAccount = '" + _userAccount + "'  order by ItemSort").List<WxMenu>();
                    if (subList.Count == 0)
                    {
                        result.button.Add(GetMenuItemJsonObject(root));
                    }
                    else
                    {
                        sub_menu_object sub_menu = new sub_menu_object();
                        sub_menu.name = root.ItemText;
                        foreach (WxMenu sub in subList)
                        {
                            sub_menu.sub_button.Add(GetMenuItemJsonObject(sub));
                        }
                        result.button.Add(sub_menu);
                    }
                }
            }

            return JsonConvert.SerializeObject(result);
        }

        protected void UpdateWeixin()
        {
            string posturl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + WeixinUtil.GetAccessToken("admin");
            string menuStr = GetMenuString();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(posturl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            byte[] postdata = Encoding.GetEncoding("UTF-8").GetBytes(menuStr);
            request.ContentLength = postdata.Length;

            Stream newStream = request.GetRequestStream();
            newStream.Write(postdata, 0, postdata.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
            var reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();//得到结果

            Response.Write(content);
        }
    }
}